package com.kth.subtranslator.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.table.DefaultTableModel;

import com.kth.subtranslator.SrtEntry;

public class SrtEntryTableModel extends DefaultTableModel {

	private final List<SrtEntry> entries;
	private final List<SrtEntry> targetEntries;

	public SrtEntryTableModel() {
		this.entries = new ArrayList<SrtEntry>();
		this.targetEntries = new ArrayList<SrtEntry>();
	}

	@Override
	public int getColumnCount() {
		return 5;
	}

	@Override
	public int getRowCount() {
		if (entries != null) {
			return entries.size();
		}
		else {
			return 0;
		}
	}

	@Override
	public Object getValueAt(int row, int column) {
		if (entries != null) {
			if (column == 0) {
				return entries.get(row).getId();
			}
			else if (column == 1) {
				return entries.get(row).getStartTime();
			}
			else if (column == 2) {
				return entries.get(row).getEndTime();
			}
			else if (column == 3) {
				return entries.get(row).getContent();
			}
			else {
				if (targetEntries.size() <= row) {
					return "";
				}
				return targetEntries.get(row).getContent();
			}
		}
		else {
			return "";
		}
	}

	public boolean addSrtEntry(SrtEntry entry) {
		return entries.add(entry);
	}

	public boolean addSrtEntries(List<SrtEntry> subEntries) {
		return entries.addAll(subEntries);
	}

	@Override
	public String getColumnName(int column) {
		if (column == 0) {
			return "#";
		}
		else if (column == 1) {
			return "Start Time";
		}
		else if (column == 2) {
			return "End Time";
		}
		else if (column == 3) {
			return "Original";
		}
		else if (column == 4) {
			return "Translation";
		}
		else {
			return "";
		}

	}

	public void addTargetSrtEntries(List<SrtEntry> srtEntries) {
		this.targetEntries.addAll(srtEntries);
	}

	@Override
	public boolean isCellEditable(int row, int column) {
		if (column == 0 ) {
			return false;
		}
		else {
			return true;
		}
	}

	@Override
	public void setValueAt(Object aValue, int row, int column) {
		if (column == 1) {
			targetEntries.get(row).setStartTime(aValue.toString());
			entries.get(row).setStartTime(aValue.toString());
		}
		else if (column == 2) {
			targetEntries.get(row).setEndTime(aValue.toString());
			entries.get(row).setEndTime(aValue.toString());
		}
		else if (column == 3) {
			entries.get(row).setContent(aValue.toString());
		}
		else {
			if (targetEntries.size() > row) {
				targetEntries.get(row).setContent(aValue.toString());
			}
		}
	}

	public void clearSourceSrtEntries() {
		entries.clear();
	}

	public void clearTargetSrtEntries() {
		targetEntries.clear();
	}

	public List<SrtEntry> getTargetEntries() {
		return Collections.unmodifiableList( targetEntries );
	}

	public List<SrtEntry> getSourceEntries() {
		return Collections.unmodifiableList( entries );
	}


}
